package com.example.demo.config;

import com.example.demo.security.filter.LoginFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;

import java.util.HashMap;

/**
 * @BelongsProject: demo
 * @BelongsPackage: com.example.demo.config
 * @Author: HUI
 * @CreateTime: 2022-03-11 17:10
 * @Description:
 */


@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    UserDetailsService userDetailsService;


    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    //自定义 AuthenticationManager，当做默认 ProvideManger（parent）
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(this.getPasswordEncoder());
    }

    //对外暴露自定义的 AuthenticationManager
    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


    @Bean
    public LoginFilter getLoginFilter() throws Exception {
        LoginFilter filter = new LoginFilter();
        filter.setFilterProcessesUrl("/doLogin");//指定登录接口
        filter.setUsernameParameter("uname");//指定接收 json 用户名 key
        filter.setPasswordParameter("passwd");//指定接收 json 密码 key

        filter.setAuthenticationManager(authenticationManagerBean());//替换默认的 AuthenticationManager
        //验证成功处理
        filter.setAuthenticationSuccessHandler((request, response, authentication) -> {
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg", "登录成功");
            result.put("用户信息", authentication.getPrincipal());
            response.setStatus(HttpStatus.OK.value());
            response.setContentType("application/json;charset=utf-8");
            String s = new ObjectMapper().writeValueAsString(result);
            response.getWriter().println(s);
        });
        //验证失败处理
        filter.setAuthenticationFailureHandler((request, response, exception) -> {
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg", "登录失败");
            result.put("失败信息", exception.getMessage());
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            response.setContentType("application/json;charset=utf-8");
            String s = new ObjectMapper().writeValueAsString(result);
            response.getWriter().println(s);
        });

        return filter;
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/vc.jpg").permitAll()//放行验证码
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                //设置未认证时的返回
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> {
                    response.setContentType("application/json;charset=utf-8");
                    response.setStatus(HttpStatus.UNAUTHORIZED.value());
                    response.getWriter().println("请先认证！");
                })
                .and()
                //设置注销登录接口与方法
                .logout()
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/doLogout", HttpMethod.GET.name()),
                        new AntPathRequestMatcher("/doLogout", HttpMethod.DELETE.name())
                ))
                //设置注销登录成功后的返回
                .logoutSuccessHandler((request, response, authentication) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "注销成功");
                    result.put("用户信息", authentication.getPrincipal());
                    response.setStatus(HttpStatus.OK.value());
                    response.setContentType("application/json;charset=utf-8");
                    String s = new ObjectMapper().writeValueAsString(result);
                    response.getWriter().println(s);
                })
                .and()
                .csrf().disable();


        //at：用某个 Filter 替换过滤器链中哪个 Filter
        //before：放在过滤器链中哪个 Filter 之前
        //after：放在过滤器链中哪个 Filter 之后
        http.addFilterAt(this.getLoginFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
